<template>
	<text class="counter-main__txt"
		:style="{color}">{{formatTime || '00天00时00分'}}</text>
</template>

<script setup>
	import {
		onMounted,
		onUnmounted,
		ref,
	} from 'vue';
	import {
		onHide,
		onShow,
		onUnload
	} from '@dcloudio/uni-app'
	const $emit = defineEmits(['counterOver'])
	const props = defineProps({
		time: {
			type: String,
			default: ''
		},
		color: {
			type: String,
			default: ''
		}
	})
	const formatTime = ref('')
	const timer = ref(null)
	onMounted(() => {
		init()
	})


	const formatDatetime = (time) => {
		if (!time) return
		clearInterval(timer.value)
		let res = 0
		const showTime = () => {
			if (time < 0) {
				clearInterval(timer.value)
				$emit('counterOver')
			}
			res = changeDateTime(time)
			return res
		}
		timer.value = setInterval(() => {
			console.log('倒计时')
			time -= 1000
			res = showTime()
			formatTime.value = res
		}, 1000)
	}

	const changeDateTime = (time) => {
		const h = padWidthZero((Math.floor(time / 1000 / 60 / 60) % 24))
		const m = padWidthZero((Math.floor(time / 1000 / 60 % 60)))
		const s = padWidthZero((Math.floor(time / 1000 % 60)))
		return h + '时' + m + '分' + s + '秒'
	}

	const padWidthZero = (data) => {
		return data < 10 ? '0' + data : data
	}

	const init = () => {
		formatTime.value = formatDatetime(props.time)
	}

	defineExpose({
		clearTimer() {
			console.log('clearTimer')
			clearInterval(timer.value)
		},
		name: "展示功能",
		init
	})
</script>

<style lang="scss"
	scoped>
	.counter-main {
		&__txt {
			// color: darkred;
			font-size: 24rpx;
		}
	}
</style>